package com.ruoyi.system.config;


import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;

import com.ruoyi.system.domain.DsStoragemanagement;
import com.ruoyi.system.service.IDsStoragemanagementService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
public class AliPayController {
    //    private static final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
//    private static final String FORMAT = "JSON";
//    private static final String CHARSET = "UTF-8";
//    //签名方式
//    private static final String SIGN_TYPE = "RSA2";
    @Autowired
    private IDsStoragemanagementService dsStoragemanagementService;
    @Resource
    private AliPayConfig aliPayConfig;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/pay") // &subject=xxx&traceNo=xxx&totalAmount=xxx
    public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(AliPayApiConfig.URL, AliPayApiConfig.APP_ID,
                AliPayApiConfig.PRIVATE_KEY, AliPayApiConfig.FORMAT, AliPayApiConfig.CHARSET, AliPayApiConfig.APLIAY_PUBLIC_KEY, AliPayApiConfig.SIGN_TYPE);


        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
        request.setNotifyUrl(AliPayApiConfig.ONTIFYURL);
        JSONObject bizContent = new JSONObject();
        bizContent.set("out_trade_no", aliPay.getRnumber());  // 我们自己生成的订单编号
        bizContent.set("total_amount", aliPay.getAmount()); // 订单的总金额
        bizContent.set("subject", aliPay.getVehicleInfo());   // 支付的名称
        bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置
        request.setBizContent(bizContent.toString());

        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + AliPayApiConfig.CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();

    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        System.out.println("111111111111111111111111");
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");
            DsStoragemanagement ds = new DsStoragemanagement();
            String aine = (String) redisTemplate.opsForHash().get("vehicle_info", "amount");
            String mind = (String) redisTemplate.opsForHash().get("vehicle_info", "pduanid");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            ds.setDeliveryDateTime(sdf.parse((String) redisTemplate.opsForHash().get("vehicle_info", "deliveryDateTime")));
            ds.setAmount(Long.valueOf(aine));
            ds.setOrdernumber((String) redisTemplate.opsForHash().get("vehicle_info", "Ordernumber"));
            ds.setStorageId(Long.valueOf(mind));
            long i = 1;
            ds.setOperationType(i);
            int ida = dsStoragemanagementService.updateDsStoragemanagement(ds);
            if (ida==1){
                if (redisTemplate != null) {
                    redisTemplate.opsForHash().put("vehicle", "id", "0");
                }
            }
        }
        return "success";
    }
}
